import strHtml from "./PostDetailsPage.html";
import { DomUtils } from "../../utils/DomUtils";
import { communityService } from "../../services/communityService"; // 导入 communityService

export class PostDetailsPage {
  constructor(postData = null) {
    this.dom = null;
    this.post = postData || JSON.parse(localStorage.getItem("selectedPost"));
    this.currentUser = JSON.parse(localStorage.getItem("currentUser"));
    this.replyToIndex = null;
    this.comments = []; // 评论数据，将从后端获取
  }

  async render() {
    this.dom = DomUtils.convertToDom(strHtml);

    //  如果 post 数据不完整，则从后台重新获取
    if (!this.post || !this.post.user || !this.post.user.avatar) {
      const response = await communityService.getPostById(this.post?.postId);
      this.post = response.data;
    }

    setTimeout(() => {
      if (!this.post || !this.post.postId) {
        console.warn("post 数据未准备好，跳过评论加载");
        return;
      }

      this._fetchComments()
        .then(() => {
          this._renderPost();
          this._renderComments();
          this._bindEvents();
        })
        .catch((err) => {
          console.error("加载评论失败：", err);
        });
    }, 0);

    return this.dom;
  }

  async _fetchComments() {
    try {
      console.log("准备请求评论，postId=", this.post?.postId);
      const response = await communityService.getCommentsByPost(
        this.post.postId
      );
      const flatComments = response || [];
      console.log("原始评论数据：", flatComments);

      // 构建 commentId -> comment 映射
      const commentMap = {};
      flatComments.forEach((c) => {
        c.replies = [];
        commentMap[c.commentId] = c;
      });

      // 构建树结构：一级评论放 this.comments，子评论塞进 replies
      const topLevelComments = [];
      flatComments.forEach((c) => {
        if (c.parentCommentId) {
          const parent = commentMap[c.parentCommentId];
          if (parent) {
            parent.replies.push(c);
          }
        } else {
          topLevelComments.push(c);
        }
      });

      this.comments = topLevelComments;
      console.log("构建后的评论树：", this.comments);
    } catch (error) {
      console.error("获取评论失败:", error);
    }
  }

  _renderPost() {
    const container = this.dom.querySelector("#post-detail");
    container.innerHTML = `
      <div class="d-flex align-items-center mb-3">
        <img src="data:image/jpeg;base64,${
          this.post.user.avatar
        }" class="rounded-circle me-3" style="width: 50px; height: 50px;">
        <div>
          <div class="fw-bold">${this.post.user.username}</div>
          <small class="text-muted">${this._formatTime(
            this.post.createTime
          )}</small>
        </div>
      </div>
      <h5 class="fw-semibold mb-2">${this.post.title}</h5>
      <p class="text-body">${this.post.content}</p>
      ${
        this.post.imageUrl
          ? `<img src="${this.post.imageUrl}" class="img-fluid rounded-4 shadow-sm mt-3">`
          : ""
      }
    `;
  }

  _renderComments() {
    const list = this.dom.querySelector("#comment-list");
    list.innerHTML = "";

    console.log("将要渲染的评论：", this.comments);

    this.comments.forEach((c, i) => {
      const div = document.createElement("div");
      div.className = "card border-0 mb-3 shadow-sm rounded-3 p-3";

      // 构建一级评论 HTML
      div.innerHTML = `
        <div class="d-flex justify-content-between align-items-center mb-1">
          <strong>${c.user?.username || "匿名"}</strong>
          <div class="d-flex align-items-center gap-2">
            <small class="text-muted">${this._formatTime(c.createTime)}</small>
            ${
              c.user?.userId === this.currentUser?.userId
                ? `<button class="btn btn-sm btn-close delete-comment" title="删除" data-index="${i}"></button>`
                : ""
            }
          </div>
        </div>
        <p class="mb-2">${c.content}</p>
        <div class="text-end">
          <button class="btn btn-sm btn-light d-inline-flex align-items-center text-primary reply-btn" data-index="${i}">
            <i class="bi bi-reply-fill me-1"></i> 回复
          </button>
        </div>
        <div class="ms-4 mt-3" id="reply-list-${i}"></div>
      `;

      // 渲染子回复
      const replyList = div.querySelector(`#reply-list-${i}`);
      (c.replies || []).forEach((r, j) => {
        const rEl = document.createElement("div");
        rEl.className = "border-start ps-3 mb-2";

        rEl.innerHTML = `
          <div class="d-flex justify-content-between align-items-center">
            <strong>${r.user?.username || "匿名"}</strong>
            <div class="d-flex align-items-center gap-2">
              <small class="text-muted">${this._formatTime(
                r.createTime
              )}</small>
              ${
                r.user?.userId === this.currentUser?.userId
                  ? `<button class="btn btn-sm btn-close delete-reply" title="删除回复" data-index="${i}" data-reply-index="${j}"></button>`
                  : ""
              }
            </div>
          </div>
          <p class="mb-1">${r.content}</p>
        `;

        replyList.appendChild(rEl);
      });

      list.appendChild(div);
    });
  }

  _bindEvents() {
    const input = this.dom.querySelector("#comment-input");
    const submit = this.dom.querySelector("#submit-comment");

    // 状态变量：是否是回复某条一级评论
    this.replyToIndex = null;

    // 发送评论或回复
    submit.addEventListener("click", async () => {
      if (!this.currentUser || !this.currentUser.userId) {
        alert("请先登录后再评论！");
        return;
      }

      const content = input.value.trim();
      if (!content) return alert("请输入评论内容");

      // 获取 parentCommentId：如果是一级评论，null；如果是回复，指向父评论ID
      const parentCommentId =
        this.replyToIndex !== null
          ? this.comments[this.replyToIndex].commentId
          : null;

      console.log("即将提交评论，parentCommentId=", parentCommentId);

      const comment = {
        postId: this.post.postId,
        userId: this.currentUser.userId,
        content: content,
        parentCommentId: parentCommentId,
      };

      try {
        const res = await communityService.addComment(comment);
        console.log("评论提交成功：", res);
        input.value = "";
        input.placeholder = "请输入评论..."; // 重置 placeholder
        this.replyToIndex = null;
        await this._fetchComments();
        this._renderComments();
      } catch (error) {
        console.error("发布评论失败:", error);
      }
    });

    // 事件委托：处理回复与删除
    this.dom.addEventListener("click", async (e) => {
      // 点击“回复”按钮（一级评论）
      const replyBtn = e.target.closest(".reply-btn");
      if (replyBtn) {
        const index = replyBtn.dataset.index;
        this.replyToIndex = parseInt(index);
        console.log("准备回复第", this.replyToIndex, "条评论");
        input.placeholder = `回复 ${
          this.comments[this.replyToIndex].user.username
        }...`;
        input.focus();
        return;
      }

      // 删除一级评论
      const delComment = e.target.closest(".delete-comment");
      if (delComment) {
        const index = parseInt(delComment.dataset.index);
        const comment = this.comments[index];
        if (comment.user.userId !== this.currentUser.userId) {
          alert("只能删除自己的评论！");
          return;
        }

        if (confirm("确定要删除该评论及其回复吗？")) {
          await communityService.deleteComment(comment.commentId);
          await this._fetchComments();
          this._renderComments();
        }
      }

      // 删除二级回复
      const delReply = e.target.closest(".delete-reply");
      if (delReply) {
        const i = parseInt(delReply.dataset.index);
        const j = parseInt(delReply.dataset.replyIndex);
        const reply = this.comments[i].replies[j];

        if (reply.user.userId !== this.currentUser.userId) {
          alert("只能删除自己的回复！");
          return;
        }

        if (confirm("确定要删除这条回复吗？")) {
          await communityService.deleteComment(reply.commentId);
          await this._fetchComments();
          this._renderComments();
        }
      }
    });
  }

  _formatTime(date) {
    const diff = Math.floor((Date.now() - new Date(date)) / 1000);
    if (diff < 60) return "刚刚";
    if (diff < 3600) return `${Math.floor(diff / 60)} 分钟前`;
    if (diff < 86400) return `${Math.floor(diff / 3600)} 小时前`;
    const d = new Date(date);
    return `${d.getFullYear()}-${d.getMonth() + 1}-${d.getDate()}`;
  }
}
